
    //检测scroll 状态
    function checkScroll( bus ) {
        var scrollTop = window.pageYOffset
            || window.scrollY
            || document.documentElement.scrollTop
            || document.body.scrollTop
            || 0;

        if ( scrollTop > 1 ){
            bus.emit('scrollTop','add');
        }

        if ( scrollTop <= 1) {
            bus.emit('scrollTop', 'cancel');
        }
    }

    //设置导航栏固定
    function setFixed( key ) {
        var types = {
                add : ['addClass','slideDown'],
                cancel : ['removeClass','slideUp']
            },
            $toolbar = $('.common-toolbar'),
            $header = $('.common-header'),
            $rightContainer = $('.common-right'),
            typeName = types[key][0];


        $toolbar[typeName]('common-toolbar-fixed');
        $header[typeName]('common-header-hidden');
        $rightContainer[typeName]('common-right-fixed');
    }

    //回到顶部
    function backTopShow( key ) {
        var types = {
                add: 'fadeIn',
                cancel: 'fadeOut'
            },
            typeName = types[key],
            $backTop = $('#backTop');
        $backTop[typeName]("fast");
    }

    //切换面板
    function changeTabs ( curTabId ){
        var tabState =  {
                tab0: {
                    id: 0,
                    title: "玩家社区账号",
                    submitBtn: '登录',
                    accountPlh: '账号/手机号',
                    pwPlh: '密码',
                    bottomBtn: '用户注册',
                    aimTab: 1,
                    bottomBtnClass: 'panel-row-active',
                    url:'/welcome/ajax_login'
                },
                tab1: {
                    id: 1,
                    title: "账号注册",
                    submitBtn: '注册',
                    accountPlh: '输入6-12位账号，支持字母和数字',
                    pwPlh: '密码',
                    registerInfo:{
                        name: '请输入姓名',
                        IDcard: '请输入18位身份证号',
                        mobile: '请输入11位手机号码'
                    },
                    // bottomBtn: '手机号码注册',
                    aimTab: 2,
                    bottomBtnClass: 'panel-row-active',
                    url:'/welcome/ajax_regist'
                },
                tab2: {
                    id: 2,
                    title: "忘记密码",
                    submitBtn: '确定',
                    accountPlh: '手机号',
                    pwPlh: '设置密码',
                    bottomBtn: false,
                    url:'/welcome/ajax_forget'
                },
                tab3: {
                    id: 3,
                    title: "手机注册",
                    submitBtn: '注册',
                    accountPlh: '手机号',
                    pwPlh: '设置密码',
                    bottomBtn: '一起玩吧账号注册',
                    aimTab: 1,
                    bottomBtnClass: 'panel-row-center panel-row-active',
                    url:'/welcome/ajax_regist'
                }
            },

            curTab = tabState[ curTabId ];

        loginUrl = curTab.url;

        var template = `<div class="common-layer-content login-content">
                            <div class="common-layer-title login-title">${ curTab.title }</div>
                            <div class="common-layer-panel login-panel">
                                ${ curTab.id !== 0
                                    ? `<div class="login-type"><div class="panel-row"><a name="tab0">账号登录</a></div></div>`
                                    : ''
                                }
                                <div>
                                    <div class="input-wrapper"><input name=${ curTab.id === 2 ? "mobile"  : "username" } value="" type="text" placeholder="${curTab.accountPlh}"></div>
                                    ${ curTab.id === 2 || curTab.id === 3
                                        ? `<div class="input-wrapper  login-verify">
                                                <input type="text" value="" placeholder="输入验证码" name="code">
                                                <div id="forgetVerifyBtn" class="login-btn login-btn-disabled">获取验证码</div>
                                            </div>`
                                        : ''
                                     }
                                    <div class="input-wrapper"><input name="password" value="" type="password" placeholder="${curTab.pwPlh}"></div>
                                    ${(function(){
                                        var html = '', key;
                                        if(curTab.id === 1){
                                            for( key in curTab.registerInfo ){
                                                html += `<div class="input-wrapper"><input name="${key}" value="" type="text" placeholder="${curTab.registerInfo[key]}"></div>`;
                                            }
                                        }
                                        return html;
                                    })()}
   
                                </div>
                                <div class="login-warning" style="display: none"></div>
                                ${  curTab.id !== 2
                                    ? curTab.id !== 0
                                        ? `<div class="panel-row panel-col-left" id="permit">
                                                <div class="login-agree">
                                                    <input type="checkbox" class="iconfont icon-okbtn">我已同意<a href="/aboutus/clause.html" target="_blank" style="color: #13b998">《用户协议》</a>
                                                </div>
                                            </div>`
                                        : `<div class="panel-row">
                                                <a name="tab2">忘记密码？</a>
                                           </div>`
                                    : ''
                                }
                                <button ${ curTab.id !== 0 
                                            ? 'disabled class="input-wrapper login-btn login-btn-disabled" ' 
                                            : 'class="input-wrapper login-btn"'
                                        } id="submitBtn" >
                                    ${ curTab.submitBtn }
                                </button>
                                ${ curTab.bottomBtn
                                    ? `<div class= " ${curTab.bottomBtnClass ? 'panel-row ' + curTab.bottomBtnClass : 'panel-row'}">
                                            <a name= "${ 'tab' + curTab.aimTab }">${ curTab.bottomBtn }</a>
                                       </div>`
                                    : ''
                                }
                            </div>
                        </div>`;

        $('.login-content').replaceWith( template );
        reBindEvent();
    }

    //提交表单
    function submitForm($warn , data ) {
        if ( loginUrl ){
            $.ajax({
                type: "POST",
                url: loginUrl,
                data: data,
                dataType:"json",
                success: function (res) {
                    if (res.ret === 0) {
                        window.location.reload();
                    } else {
                        showError($warn, res.msg )
                    }
                }
            });
        }
    }

    //表单验证
    function checkInfo() {
        var inputArr =[{
                type: 'username',
                title: '账号',
                reg: /^[a-zA-Z0-9]+$/g,
                regErrText: '账号只能由字母和数字组成'
            },{
                type: 'password',
                title: '密码',
                reg: /^.{6,14}$/g,
                regErrText: '请输入6到14位的密码'
            },{
                type: 'name',
                title: '姓名'
            },{
                type: 'IDcard',
                title: '身份证号',
                reg: /^\d{17}[0-9xX]$/g,
                regErrText: '请填写正确的18位身份证号'
            },{
                type: 'mobile',
                title: '手机号',
                reg: /^\d{11}$/g,
                regErrText: '请填写正确的11位手机号'
            },{
                type: 'code',
                title: '验证码'
            }],
        errObj = {
            err: false,
            data: {}
        };

        $.each( inputArr, function ( index, item ) {
            var $item = $('input[name="'+ item.type +'"]');
            if( $item.length !== 0 ){
                $item.removeClass('input-warning');
            }
        });

        $.each( inputArr, function ( index, item ) {
            var $item = $('input[name="'+ item.type +'"]'),
                reg = item.reg || '',
                inputValue = $item.length !== 0 ? $item.val().trim() : '';
                if( $item.length !== 0 && !inputValue ){
                    errObj.err = true;
                    errObj.errInput = $item;
                    errObj.errText = item.title + '不能为空';
                    return false;
                }else if( $item.length !== 0 && reg && !reg.test(inputValue) ){
                    errObj.err = true;
                    errObj.errInput = $item;
                    errObj.errText = item.regErrText;
                    return false;
                }else if( $item.length !== 0 ){
                    errObj.data[item.type] = inputValue;
                }
        });
        return errObj;
    }

    //绑定表单发送按钮
    function bindSubmitBtn() {
        var $submitBtn =  $('#submitBtn'),
            $warn = $('.login-warning');

        $submitBtn.on('click keydown', function (e) {
            var infoObj = checkInfo();
            if(e.type === 'click' || e.keyCode === 13 ){
                if( !infoObj.err ){
                    $warn.hide();
                    submitForm( $warn, infoObj.data );
                }else{
                    showError( $warn, infoObj.errText, infoObj.errInput );
                }
            }
        });
    }

    //发送验证码
    function bindSendVerifyBtn() {
        var $sendVerifyBtn = $('#forgetVerifyBtn');
        if( $sendVerifyBtn.length ){
            $sendVerifyBtn.off('click');
            $sendVerifyBtn.on('click', function () {
                // 检查手机号码是否正确

                var $btn = $(this);
                var $mobile = $('[name="mobile"]'),
                    mobile = $mobile.val().trim(),
                    mobileReg  = /^\d{11}$/g;
                if( $mobile.length !== 0 && !mobileReg.test( mobile ) ){
                    showError( $('.login-warning'),'请填写正确的手机号', $mobile );
                }else{
                    // 通过验证，发送验证码
                    $mobile.removeClass('input-warning');
                    $('.login-warning').hide();
                    // loginSendVerifyCode( mobile );
                    if(globalIntervalLoginNum >= 60){
                        $.ajax({
                            type: "POST",
                            url: '/welcome/send_ma/forget',
                            data: {
                                mobile: mobile
                            },
                            dataType:"json",
                            success: function (res) {
                                if( res.ret === 0 ){
                                }else{
                                    alert( res.msg );
                                    reset();
                                }
                            }
                        });


                        globalIntervalLoginTimer = setInterval(function () {
                            $btn.text( globalIntervalLoginNum-- + '秒后重发');
                            if(globalIntervalLoginNum < 0 ){
                                reset();
                            }
                        },1000);

                        $btn.addClass('login-btn-disabled');
                    }
                }
            });
        }
        //设置样式
    }

    //展示表单错误信息
    function showError( $warn, text, errInput ) {
        var input = errInput ? errInput : undefined;
        if ( input ){
            input.addClass('input-warning');
        }

        $warn.show();
        $warn.text( text );
    }

    //切换登录注册面板
    function bindChangeTabEvent( ){
        var $tabBtns = $('.login-layer .panel-row a');

        $tabBtns.off('click');
        $tabBtns.on('click', function (e) {
            e = e || event;
            e.stopPropagation();
            var curTab = $( this ).attr('name');
            changeTabs( curTab );
        })
    }

    //重置登录面板信息
    function reset(){
        $('#permit').find('input[type="checkbox"]').prop( "checked", false );
        globalIntervalLoginNum = 60;
        $('#forgetVerifyBtn').removeClass('login-btn-disabled').text('发送验证码');
        clearInterval(globalIntervalLoginTimer);

    }

    //绑定关闭按钮
    function bindCloseBtn( loginModel ) {
        var $closeBtn = $('.login-close-btn');

        $closeBtn.on('click',function (e) {
            e = e || event;
            e.preventDefault();
            loginModel.close();
        });
    }

    //绑定许可功能
    function bindCheckPermit() {
        var $check = $('#permit').find('input[type="checkbox"]'),
            $varifyInput = $('[name="code"]'),
            $mobile = $('[name="mobile"]'),
            $verifyBtn = $('#forgetVerifyBtn'),
            $submitBtn =  $('#submitBtn');
        if( $check.length !== 0 ){
            $check.off('click');
            $check.on('click', function () {
                if( $check.is(':checked') ) {
                    $submitBtn.removeAttr('disabled');
                    $submitBtn.removeClass('login-btn-disabled');
                }else{
                    $submitBtn.addClass('login-btn-disabled');
                    $submitBtn.attr('disabled','disabled');
                }
            });
        }
        if( $varifyInput.length !== 0 ){
            $varifyInput.off('input');
            $varifyInput.on('input', function () {
                if( $varifyInput.val().trim() !== '' ) {
                    $submitBtn.removeAttr('disabled');
                    $submitBtn.removeClass('login-btn-disabled');
                }else{
                    $submitBtn.addClass('login-btn-disabled');
                    $submitBtn.attr('disabled','disabled');
                }
            });
        }
        if( $mobile.length !== 0 ){
            $mobile.off('input');
            $mobile.on('input', function () {
                if( $mobile.val().trim() !== '' ) {
                    $verifyBtn.removeClass('login-btn-disabled');
                }else{
                    $verifyBtn.attr('disabled','disabled');
                }
            });
        }
    }

    //绑定打开登录注册面板功能
    function bindOpenBtn( loginModel ) {
        var $btn = $('.login-btn-open');
        $btn.off('click');
        $btn.on('click', function (e) {
            e = e || event;
            //获取属性
            var curTab = $( e.target ).attr('name');
            e.stopPropagation();
            changeTabs( curTab );
            loginModel.open();
        });
    }

    //登录注册按钮
    function openLoginPanel( curTab, loginModel ) {
        changeTabs( curTab );
        loginModel.open();
    }

    //重新绑定登录表单
    function reBindEvent(){
        bindChangeTabEvent();
        bindCheckPermit();
        bindSendVerifyBtn();
        bindSubmitBtn();
}

    //发送搜索
    function sendSearch() {
        var keyword = $('#headSearchInput').val().trim();
        if( keyword ){
            window.location.href = '/search?keyword=' + keyword;
        }

    }




    var loginUrl = '';

    var bus = new Event();

    var $login = '';

    var loginModel = '';

    var globalIntervalLoginNum = 60;

    var globalIntervalLoginTimer = null;


$( document ).ready(function () {
    //监听
    bus.on( 'scrollTop',setFixed );
    bus.on( 'scrollTop',backTopShow );
    bus.on( 'openLogin', openLoginPanel );

    //检查当前scroll
    checkScroll( bus );

    //页面滚动功能
    $( window ).on('scroll',function (e) {
       checkScroll( bus );
    });

    //回到顶部
    $('#backTop').on('click',function () {
        $('body,html').animate({ scrollTop: 0 },500,'swing');
    });

    $login = $('.login-layer');

    //创建登录弹窗
    loginModel = $login.SUIModel({
        shade: '.login-shade'
    });

    //绑定按钮
    bindOpenBtn( loginModel );
    bindCloseBtn( loginModel );

    //侧边刷新加载功能
    var refreshTmpl =
        `<li class="common-game-item">
            <a class="common-game-avatar" href="/game/detail/{% data.id %}" target="_blank">
                <img data-original="{% data.img %}">
            </a>
            <div class="common-game-detail">
                <div class="common-game-info">
                    <div class="common-game-name">
                        <a class="ellipse" href="/game/detail/{% data.id %}" target="_blank">{% data.name %}</a>
                    </div>
                    <div class="common-game-additional">
                        <span>{% data.cate_id %}</span>
                        {% if(data.tags && data.tags.length){ %}
                        <span>{% data.tags[0] %}</span>
                        {% } %}
                    </div>
                </div>
                <a class="common-game-btn"  href="/game/detail/{% data.id %}" target="_blank">查看</a>
            </div>
        </li>`;

    var refreshGameList = new LoadData({
        btn: '.refresh',
        lists: '#gameNewList',
        listType: 'game',
        url: '/game/ajax_game_list/',
        page: 2,
        paramLimit: 5,
        template: refreshTmpl,
        method: 'replaceWith',
        handleFn: {
            'cate_id': utils.setDataItem.bind(utils),
            'tags': utils.setDataItem.bind(utils)
        },
        afterRender: function () {
            $('img').lazyload({
                effect: "fadeIn",
                effectspeed: 1500
            })
        },
        renderFn: function ( tmpl, data ) {
            var html = '<ul class="common-aside-game" id="gameNewList">';
            $.each( data, function ( index, item ) {
                html += utils.parseTmpl( tmpl , item );
            });
            html += '</ul>';

            return html;
        },
        fullLoadFn: function ( me ) {
            refreshGameList.page = 1;
        }
    });


    // 图片懒加载功能
    var asideImg = $('img').lazyload({
        effect: "fadeIn",
        effectspeed: 1500
    });

    //搜索功能
    $('#headSearchInput').on({
        keydown: function (e) {
            //监听回车事件
            e = (typeof e !== 'undefined') ? window.event : e;
            if( e.keyCode === 13 ){
                sendSearch();
            }
        }
    });

    $('#headSearchBtn').on('click', function () {
        sendSearch();
    });

    //搜索框动效
    $('body').on('click', function (e) {
        e = e || event;
        // e.preventDefault();
        var $target = $( e.target ),
            $parent =  $target.parent('.common-header-search'),
            $search = $('.common-header-search');
        if( $parent.length ){
            $search.css('width','450px');
        }else{
            $search.css('width','380px');
        }
    });

});



